<?php
class DbCache {
	private $keys_prefix;

	public function __construct($options)
	{
		$this->keys_prefix	= $options['cache_key_prefix'];
		$this->db	= Database::getInstance();
		// echo "use database cache";
	}

	public function get($key)
	{
		$keyy	= md5($this->keys_prefix.$key);
		$res	= FALSE;
		$sdf	= $this->db->queryOne('SELECT data, expire FROM cache WHERE `key`=? LIMIT 1', $keyy);
		if( $sdf ) {
			if( intval($sdf['expire']) <= time() ) {
				$this->delete($key);
			}
			else {
				$tmp	= stripslashes($sdf['data']);
				if( $tmp = unserialize($tmp) ) {
					$res	= $tmp;
				}
			}
		}
		return $res;
	}

	public function set($key, $data, $ttl = 600)
	{
		$keyy	= md5($this->keys_prefix.$key);
		$data	= serialize($data);
		$exp	= time() + $ttl;
		$affected_rows	= $this->db->execute('REPLACE INTO cache SET `key`=?, data=?, expire=? ', $keyy,$data, $exp);
		return $affected_rows;
	}

	public function replace($key, $data) {
		$keyy	= md5($this->keys_prefix.$key);
		$data	= serialize($data);
		$affected_rows	= $this->db->execute('update cache SET  data=? where `key`=?',$data, $keyy);
		return $affected_rows;
	}

	public function delete($key)
	{
		$keyy	= md5($this->keys_prefix.$key);
		$affected_rows	= $this->db->execute('DELETE FROM cache WHERE `key`= ? LIMIT 1', $keyy);
		return $affected_rows > 0;
	}


	public function flush()
	{
		$time	= microtime(TRUE);
		$affected_rows	= $this->db->execute('DELETE FROM cache WHERE expire<= ?', time());
		return $$affected_rows;
	}

	public function increment($key, $value = 1) {
		$v = $this->get($key);
		$v = intval($v) + $value;
		$this->replace($key, $v);
	}

	public function decrement($key, $value = 1) {
		$v = $this->get($key);
		$v = intval($v) - $value;
		$this->replace($key, $v);
	}
}